package com.example.springboottest.controller;

import com.example.springboottest.Entity.Tb_book;
import com.example.springboottest.repository.Tb_BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookHandler {

    @Autowired
    private Tb_BookRepository tb_bookRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Tb_book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return tb_bookRepository.findAll(pageable);
    }


    @PostMapping(value = "/save")
    public String save____(@RequestBody Tb_book tb_book){
        System.out.println("==================");
        System.out.println("==================");
        System.out.println("==================");
        System.out.println(tb_book);
        Tb_book result = tb_bookRepository.save(tb_book);
        if (result != null){
            return "success";
        }else {
            return "error";
        }
    }

    @GetMapping("/findbyid/{id}")
    public Tb_book findbyid(@PathVariable("id") Integer id){
        return tb_bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Tb_book tb_book){
        System.out.println("==================");
        System.out.println(tb_book);
        Tb_book result = tb_bookRepository.save(tb_book);
        if (result != null){
            return "success";
        }else {
            return "error";
        }
    }
    @DeleteMapping("/delete/{id}")
    public void ddeletebyid(@PathVariable("id") Integer id){
        tb_bookRepository.deleteById(id);
    }
}
